package com.android.kotlincoroutinemvvmdemo.view;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import androidx.annotation.Nullable;

public class IrregularlyRadiusLoadingView extends View {
    private Path dstPath;
    //路径计算
    private PathMeasure pathMeasure;
    //画笔
    private Paint paint;
    //路径长度的比值 (0 - 1)
    private float pathDistanceRatio;

    public IrregularlyRadiusLoadingView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldW, int oldH) {
        super.onSizeChanged(w, h, oldW, oldH);

        paint = new Paint();
        paint.setStrokeWidth(10);
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true);
        paint.setColor(Color.BLACK);

        Path path = new Path();
        float radius = Math.min(w, h) / 2F;
        path.addCircle(0, 0, radius - paint.getStrokeWidth(), Path.Direction.CW);

        pathMeasure = new PathMeasure(path, false);

        dstPath = new Path();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawColor(Color.WHITE);

        int width = getWidth();
        int height = getHeight();

        //移动canvas坐标系到中心点
        canvas.translate(width / 2F, height / 2F);

        //当前截取的结束点
        float stopD = pathMeasure.getLength() * pathDistanceRatio;

        //当前截取的开始点
        float startD = (float) (stopD - ((0.5 - Math.abs(pathDistanceRatio - 0.5)) * pathMeasure.getLength()));

        dstPath.reset();
        pathMeasure.getSegment(startD, stopD, dstPath, true);

        canvas.drawPath(dstPath, paint);
    }

    public void startAnimation() {
        //计算比例的动画
        ValueAnimator ratioAnimator = ValueAnimator.ofFloat(0, 1);
        ratioAnimator.addUpdateListener(valueAnimator -> {
            pathDistanceRatio = (float) valueAnimator.getAnimatedValue();
            invalidate();
        });
        ratioAnimator.setDuration(2000);
        ratioAnimator.setRepeatMode(ValueAnimator.RESTART);
        ratioAnimator.setRepeatCount(ValueAnimator.INFINITE);
        ratioAnimator.setInterpolator(new DecelerateInterpolator());
        ratioAnimator.start();
    }
}
